import React, {Component} from 'react';
import {Select, Button, message} from "antd";
import {deepCopy, messages} from "share/common";
import Selector from "components/selector";
const Option = Select.Option;

class CostCenterList extends React.Component {

  state = {
    value: []
  };

  componentWillMount() {
    if ('value' in this.props) {
      const value = this.props.value;
      this.setState({ value: this.initValue(value) });
    }
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({ value: this.initValue(value) });
    }
  }

  initValue = value => {
    if(value.length > 3) return value;
    return value.concat([null, null, null]).splice(0,3)
  };

  onChange = (changedValue, index) => {
    const onChange = this.props.onChange;
    const { value } = this.state;
    let newValue = deepCopy(value);
    newValue.splice(index, 1, changedValue);
    onChange && onChange(newValue);
  };

  onAddCostCenter = () => {
    const onChange = this.props.onChange;
    const { value } = this.state;
    if(value.length >= 7) {
      message.error(messages('expense-16.key416')/*最多支持配置7个成本中心*/);
      return;
    }
    let newValue = deepCopy(value);
    newValue.push('');
    this.setState({ value: newValue });
    onChange && onChange(newValue);
  };

  filterOption = i => {
    const { value } = this.state;
    let flag = true;
    value.map(v => i && v && i.id && ((v.id || v.costCenterId) === i.id) && (flag = false));
    return flag;
  };

  render() {
    const { value } = this.state;
    return (
      <div className="cost-center-list">
        {
          value.map((i, index) => (
            <Selector
              type="cost_center_tenant_all"
              entity
              searchIfKeywordIsNull
              filter={this.filterOption}
              value={i ? i.name : null}
              placeholder={messages('expense-16.key417')/*请选择成本中心*/}
              onChange={changedValue => this.onChange(changedValue, index)}
            />
          ))
        }
        <Button type='link' icon='plus' onClick={this.onAddCostCenter}>{messages('expense-16.key418')/*新增成本中心行*/}</Button>
      </div>
    )
  }
}

export default CostCenterList
